package com.guodexian.controller;
import com.github.pagehelper.PageInfo;
import com.guodexian.config.QiNiuConfig;
import com.guodexian.dto.DishDto;
import com.guodexian.entity.Dish;
import com.guodexian.mapper.DishMapper;
import com.guodexian.service.DishService;
import com.guodexian.service.FileService;
import com.guodexian.vo.R;
import com.qiniu.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 类说明：<br>
 *
 * @author qfrx<br>
 * 2024/12/26 19:10<br>
 * @since 1.0 <br>
 */
@CrossOrigin()
@RestController
@RequestMapping("/admin/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private FileService fileService;
    @Autowired
    private QiNiuConfig qiNiuConfig;
    @Autowired
    private DishMapper dishMapper;

    @RequestMapping("/search")
    public R<PageInfo<Dish>> search(@RequestParam(required = false,defaultValue = "1") int pageNum,
                                        @RequestParam(required = false,defaultValue = "2")int pageSize,
                                        @RequestParam(required = false,defaultValue = "-1") int shopId,
                                        @RequestParam(required = false,defaultValue = "") String  dishName
    ){
        return R.OK.setData(dishService.search(pageNum,pageSize,shopId,dishName));
    }
    @RequestMapping("/add")
    public R  addDish(Dish dish, MultipartFile dishImgFile) throws IOException {
        if(!dishImgFile.isEmpty()){
            String ret=fileService.uploadFile(dishImgFile);
            //{"hash":"Fkrd-3s5cc0XgcdnNlbZ3LrO702w","key":"822ed9e2-b701-4603-a23b-883dc7124cc5.png"}
            //其中key就是文件名
            //需要完成json字符串转为Java对象
            String url= qiNiuConfig.getUrl()+"/"+ Json.decode(ret).get("key");
            dish.setDishImg(url);
        }
        dishService.add(dish);
        return  R.OK;
    }
    @RequestMapping("/toEdit/{dishId}")
    public R toEditDish(@PathVariable("dishId") int dishId){
        return R.OK.setData(dishService.searchById(dishId));
    }
    @RequestMapping("/update")
    public R updateDish(@RequestBody DishDto dishDto){
        dishService.modify(dishDto);
        return  R.OK;
    }
    @DeleteMapping("/{id}")
    public R deleteDish(@PathVariable("id") int id){
        dishService.deleteById(id);
        return R.OK;
    }
    @DeleteMapping("")
    public R deleteDishes(@RequestBody Integer[] ids){
        dishService.deleteByIds(ids);
        return R.OK;
    }
}
